import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:network_to_file_image/network_to_file_image.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:web_container/pages/root/guide_page.dart';
import 'package:web_container/tools/file_manager.dart';

class SplashPage extends StatefulWidget {

  const SplashPage({Key? key}): super(key: key);

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {

  // 倒计时默认 `5s`
  int _count = 5;
  // `0 未知`  `1 缓存图片`  `2 默认图`
  int _photo = 0;
  // 是否显示隐私条款
  bool _isPolicy = true;

  late Timer _timer;
  List<dynamic> _user = [];

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  void initState() {
    super.initState();
    init();
  }

  init() async {

    initCountDown();
  }

  // 启动广告相关
  initCountDown() async {

    FileManager.instance().readJson().then((value) {

      try {
        if (value.isNotEmpty && value.toString() != '[]') {
          _user = value as List;
          if (!_user.isNotEmpty) {
            _photo = 1;
            for (var i = 0; i < _user.length; i++) {
              _count = int.parse(_user[0]['summary']);
            }
          }
        } else {
          _photo = 2;
        }
      } catch (e) {
        _photo = 2;
      }

      _countDown();
      _privacyGuide();
    });
  }

  Future _countDown() async {

    _isPolicy == false
      ? Timer(const Duration(seconds: 1), () {
          _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
            _count--;
            if (_count == 0) {
              // 跳转到 `home` 页
              navigationToRoot();
            } else {
              // 刷新界面
              setState(() {});
            }
          });
        }) 
      : null;
  }

  void _launchUrl(Uri url) async {
    if (!await launchUrl(url)) throw 'Could not launch $url';
  }

  Future _privacyGuide() async {

    var _dialog = CupertinoAlertDialog(
      title: const Text('个人隐私保护指引'),
      content: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[

          Container(
            padding: const EdgeInsets.only(top: 5, bottom: 5),
            child: const Text('欢迎使用！',
              style: TextStyle(fontSize: 14.0, color: Colors.black),
              textAlign: TextAlign.left,),
          ),

          RichText(
            text: TextSpan(
              text: '        为了更好的为您提供阅读新闻、线上订报等相关服务，我们会根据您使用服务的具体功能需要，收集必要的用户信息。您可通过阅读',
              style: const TextStyle(fontSize: 14.0, color: Colors.black),
              children: <TextSpan>[
                TextSpan(
                  text: '《隐私政策》',
                  style: const TextStyle(fontSize: 14.0, color: Colors.blue),
                  recognizer: TapGestureRecognizer()..onTap = () {
                    // 前往网页
                    // https://www.xxx.com/app/privacyPolicy.html
                    _launchUrl(Uri.parse('https://www.baidu.com'));
                  }
                ),
                const TextSpan(
                  text: '、',
                  style: TextStyle(fontSize: 14.0, color: Colors.black),
                ),
                TextSpan(
                  text: '《用户使用协议》',
                  style: const TextStyle(fontSize: 14.0, color: Colors.blue),
                  recognizer: TapGestureRecognizer()..onTap = () {
                    // 前往网页
                    // https://www.xxx.com/app/privacyPolicy.html
                    _launchUrl(Uri.parse('https://www.baidu.com'));
                  }
                ),
                const TextSpan(
                  text: '和',
                  style: TextStyle(fontSize: 14.0, color: Colors.black),
                ),
                TextSpan(
                  text: '《MobTech隐私政策》',
                  style: const TextStyle(fontSize: 14.0, color: Colors.blue),
                  recognizer: TapGestureRecognizer()..onTap = () {
                    // 前往网页
                    // http://download.sdk.mob.com/2021/03/03/21/161477643974880.38.html
                    _launchUrl(Uri.parse('https://www.baidu.com'));
                  }
                ),
                const TextSpan(
                  text: '了解我们收集、使用、存储、分享等相关个人信息情况，以及对您个人隐私的保护措施。',
                  style: TextStyle(fontSize: 14.0, color: Colors.black),
                ),
              ],
            ),
            textAlign: TextAlign.left,
          ),

          Container(
            padding: const EdgeInsets.only(top: 5),
            child: const Text('        如您同意，请点击下方按钮开始接受我们的服务。',
              style: TextStyle(fontSize: 14.0, color: Colors.black),
              textAlign: TextAlign.left,
            ),
          ),
        ],
      ),

      actions: <Widget>[
        CupertinoButton(
          child: const Text('暂不使用', style: TextStyle(color: Colors.grey),), 
          onPressed: () async {
            exit(0);
          },
        ),
        CupertinoButton(
          child: const Text('同 意', style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),), 
          onPressed: () async {
            // 授权中...
            _isPolicy = false;
            await _privacyGrantResult(context);
            setState(() {
              // 保存选择状态
              // ...
              _countDown();
              Navigator.pop(context, false);
            });
          },
        ),
      ],
    );

    _isPolicy == true
      ? showDialog(
          context: context, 
          builder: (_) => _dialog,
          barrierDismissible: false
        ) 
      : null;

  }

  _privacyGrantResult(BuildContext context) async {

  }

  navigationToRoot() {

    _timer.cancel();
    // 取消定时后前往 Root 页面
    // 跳转到新页面，并等待该页面pop返回
    // Navigator.push(context, MaterialPageRoute(builder: (context) => const GuidePage()));
    // 替换当前页面并跳转到新页面
    // Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const GuidePage()));
    // 跳转到新页面并移除当前页面
    Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => const GuidePage()), (Route<dynamic> route) => false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[

          _photo == 1
            ? SizedBox(
                height: MediaQuery.of(context).size.height,
                width: MediaQuery.of(context).size.width,
                child: GestureDetector(
                  behavior: HitTestBehavior.translucent,
                  onTap: () async {
                    // 进入广告
                  },
                  child: _user[0]['addressBenNow'] != null || _user[0]['addressBenNow'] != '' 
                    ? Image.file(
                        File(_user[0]['addressBenNow']),
                        fit: BoxFit.fill,
                      ) 
                    : Image(
                        image: NetworkToFileImage(
                          url: _user[0]['headImg'][0],
                          file: File(_user[0]['addressBenNow'],),
                          debug: false,
                        ), 
                        fit: BoxFit.fill,
                      ),
                ),
              )
            : _picture(),

          _isPolicy == false
            ? Padding(
                padding: EdgeInsets.only(
                  left: MediaQuery.of(context).size.width * 5 / 6 - 20,
                  top: MediaQuery.of(context).size.height - MediaQuery.of(context).size.height / 8,
                ),
                child: Container(
                  padding: const EdgeInsets.only(
                    top: 5, bottom: 5, left: 10, right: 10,
                  ),
                  child: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      // 跳过广告
                      setState(() {
                        _count = 0;
                      });
                      navigationToRoot();
                    },
                    child: Text(
                      '跳过 $_count',
                      style: const TextStyle(
                        fontSize: 13,
                        color: Color(0xFFDDDDDD)
                      ),
                    ),
                  ),
                  decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                    border: Border.all(width: 0.6, color: const Color(0xFFEEEEEE)),
                  ),
                ),
              )
            : Container(),

        ],
      ),
    );
  }

  Widget _picture() {
    return SizedBox(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: Image.asset('lib/assets/image/splash.png', fit: BoxFit.fill,),
    );
  }
}
